<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
          <!-- 顶部表单 -->
          <el-form :inline="true" class="demo-form-inline" :model="formInline" >
            <div class="left">
                <el-form-item label="关键字"  class="gjz">
                  <el-input size="small" placeholder="请根据标题搜索" v-model="inputVal"></el-input>
                </el-form-item>
                <el-form-item label="状态" class="zt">
                  <el-select  size="small" placeholder="请选择" v-model="stateUpdate">
                    <el-option v-for="item in stateVal" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button size="small" @click="clear">清除</el-button>
                  <el-button size="small" type="primary" @click="search">查询</el-button>
                </el-form-item>
            </div>
                <el-form-item>
                  <div class="right">
                    <el-button type="success" icon="el-icon-edit" size="small" @click="add('新增文章')">新增技巧</el-button>
                  </div>
                </el-form-item>
          </el-form>

          <!-- 数据 -->
          <el-alert
            :title="`总共有${total}条数据`"
            type="info"
            :closable="false"
            show-icon
            class="datanumber">
          </el-alert>

          <!-- 表格 -->
          <el-table :data="tableData" style="width: 100%" >
            <el-table-column type="index" :index="indexMethod" label="序号" width="120px"></el-table-column>
            <el-table-column prop="title" label="文章标题" width="330px">
              <template #default="{row}">
                  <!-- <span>{{ row.title }}</span> -->
                  <!-- <span>{{row.title}}<i class="el-icon-film" v-show="row.videoURL" @click="addVideo(row)" style="color: blue"></i></span> -->
                  <span>{{row.title}} <a><i class="el-icon-film" v-show="row.videoURL" @click="addVideo(row)" style="color: blue"></i></a></span>
              </template>
            </el-table-column>
            <el-table-column prop="visits" label="阅读数" width="150px"></el-table-column>
            <el-table-column prop="username" label="录入人" width="150px"></el-table-column>
            <el-table-column prop="createTime" label="录入时间" width="180px">
              <template #default="{row}">
                {{ formDate(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="state" label="状态" width="150px">
              <template #default="{row}">
                {{ formState(row.state) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{row}">
                  <el-button type="text" @click="preview(row)">预览</el-button>
                  <el-button type="text" @click="forbidden(row.id, row.state)" > {{ row.state === 0 ? "启用" : "禁用" }}</el-button>

                                                  <!-- 修改 -->
                  <el-button type="text" v-if="row.state === 1" :disabled="true" >修改</el-button>
                  <el-button type="text" v-else :disabled="false" @click="upd('修改文章',row)">修改</el-button>

                                                  <!-- 删除 -->
                  <el-button type="text" v-if="row.state === 1" :disabled="true" >删除</el-button>
                  <el-button type="text" v-else :disabled="false" @click="del(row)">删除</el-button>

                </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-row>
            <el-pagination
              background
              class="page"
              :current-page="pageData.page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageData.pagesize"
              layout="prev, pager, next, sizes, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              >
            </el-pagination>
          </el-row>
      </el-card>

      <!-- 视频按钮 -->
      <div v-if="showVideo">
            <div class="xBox" @click="showVideo = false"><i class="el-icon-close"></i></div>
            <div class="videoBox">
              <video :src="video" controls autoplay></video>
            </div>
      </div>

      <!-- 预览弹窗 -->
      <el-dialog title="预览文章" width="50%" height="50%" :visible="seedialogVisible" :before-close="closeSeeDialog" class="seeDialog">
        <div style="font-weight:700; font-size:20px;">{{detailList.title}}</div>
        <div style="margin-top: 15px;">
          <span>{{ formDate(detailList.createTime) }}</span>
          <span style="margin-left: 30px;">超级管理员 </span>
          <span style="margin-left: 30px;"><i class="el-icon-view el-icon--right"></i> {{detailList.visits}}</span>
        </div>
        <div v-html="detailList.articleBody" class="body"></div>
      </el-dialog>

      <!-- 新增文章弹窗 -->
      <el-dialog  :title="title" width="50%" height="50%" :visible="articlesVisible" @close="close" class="seeDialog" prop="content">
          <el-form ref="form" label-width="80px" :model="ruleForm" :rules="rules">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="ruleForm.title"></el-input>
            </el-form-item>
            <!-- 富文本 -->
              <el-form-item label="文章内容" prop="articleBody">
                  <quill-editor class="editor" v-model="ruleForm.articleBody" ></quill-editor>
              </el-form-item>
            <!-- 视频地址 -->
            <el-form-item label="视频地址" prop="videoURL">
              <el-input v-model="ruleForm.videoURL"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">提交</el-button>
              <el-button @click="close">取消</el-button>
            </el-form-item>
          </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { list as getListAPI, add, remove as del, update as upd, detail, changeState } from '@/api/hmmm/articles'
// 引入插件
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor' // 富文本编辑器
import dayjs from 'dayjs'
export default {
  data () {
    return {
      // *********************************** 表格数据 **************************
      tableData: [],
      formData: {
        entryTime: '' // 录入时间
      },
      showVideo: false, // 视频预览
      // *********************************** 表单 ******************************
      formInline: {
        keyword: '', // 输入框输入内容
        state: '' // 下拉框状态
      },
      inputVal: '',
      stateUpdate: '',
      stateVal: [
        {
          label: '启用',
          value: '1'
        },
        {
          label: '禁用',
          value: '0'
        }
      ],
      // *********************************** 分页 ******************************
      pageData: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      //  ******************************** 预览弹窗 *****************************
      seedialogVisible: false,
      detailList: [],
      //  ******************************** 新增弹窗 *****************************
      articlesVisible: false,
      title: '', // 弹窗标题
      //  ******************************** 富文本编辑器 *************************
      // 输入框
      ruleForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            [
              'bold',
              'italic',
              'underline',
              'strike',
              'link',
              'image',
              'code-block'
            ], // toggled buttons
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ font: [] }], // 字体
            // [{ size: ['small', 'normal', 'large', 'huge'] }],
            [{ color: [] }, { background: [] }] // 字体颜色，字体背景颜色
          ]
        }
      }
    }
  },
  // 注册富文本组件
  components: {
    quillEditor
  },
  created () {
    this.get_articleLists()
  },
  methods: {
    // *********************************** 表格数据 **************************
    // 获取列表数据
    async get_articleLists () {
      const { data } = await getListAPI(this.pageData)
      // console.log(data)
      this.total = data.counts
      this.tableData = data.items
      console.log(this.tableData)
    },
    // 控制序号
    indexMethod (index) {
      return index + 1 + (this.pageData.page - 1) * this.pageData.pagesize
    },
    // 格式化时间
    formDate (row) {
      return dayjs(row).format('YYYY-MM-DD HH:mm:ss')
    },
    // 状态
    formState (row) {
      const map = {
        1: '已启用',
        0: '已禁用'
      }
      return map[row]
    },
    // 禁用按钮
    async forbidden (id, state) {
      if (state === 0) {
        state = 1
      } else {
        state = 0
      }
      await changeState({ id: id, state: state })
      this.$message.success('操作成功')
      this.get_articleLists()
    },
    // 视频按钮
    addVideo (data) {
      this.showVideo = true
      this.video = data.videoURL
    },
    // 预览弹窗
    async preview (row) {
      this.seedialogVisible = true
      const res = await detail(row)
      // console.log(data);
      this.detailList = res.data
      // console.log(this.detailList)
    },
    // 关闭预览弹窗
    closeSeeDialog () {
      this.seedialogVisible = false
    },
    // 删除功能
    del (id) {
      // 1、询问下：
      this.$confirm('确定删除此数据么?', '删除提示')
        .then(async () => {
          // 2、调用删除接口 传入id
          await del(id) // 把数据库里面数据删除了
          this.$message.success('删除成功')

          // 前端的数据显示现在还有一条：过时的数据，是刚才删除数据库那条数据最后一次痕迹！
          if (this.tableData.length === 1 && this.pageData.page > 1) {
            this.page-- // 回到上一页
          }
          // 3、重新调用列表
          this.get_articleLists()
        })
    },
    // 编辑功能
    upd (key, one) {
      // 1、弹窗出现
      this.articlesVisible = true
      this.title = key

      this.ruleForm = { ...one }
    },

    // ************************************** 表单 **************************
    // 清除输入框
    clear () {
      this.stateUpdate = ''
      this.inputVal = ''
      this.pageData.page = 1
      this.get_articleLists()
    },
    // 搜索
    async search () {
      this.formInline.state = this.stateUpdate
      this.formInline.keyword = this.inputVal
      // console.log(this.stateUpdate, this.inputVal)
      const res = await getListAPI(this.formInline)
      this.tableData = res.data.items
      this.total = res.data.counts
    },
    // 新增文章弹窗
    add (key) {
      this.articlesVisible = true
      this.title = key
    },
    // 关闭弹窗
    close () {
      this.articlesVisible = false
      this.$refs.form.resetFields() // 重置表单
    },
    // 新增(修改)文章提交
    onSubmit () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.title === '新增文章') {
            await add(this.ruleForm) // 2、准备新增api接口
            this.$message.success('新增成功')
            this.$refs.form.resetFields() // 重置表单
          }

          if (this.title === '修改文章') {
            await upd(this.ruleForm) // 2、准备编辑api接口
            this.$message.success('修改文章成功')
          }

          this.close() // 关闭抽屉
          this.pageData.page = 1
          this.get_articleLists() // 重新获取页面数据
        } else {
          return false
        }
      })
    },

    // ************************************** 分页功能 **************************
    // 页面大小改变
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pageData.pagesize = val
      // console.log(this.pagesize)
      this.pageData.page = 1
      this.get_articleLists()
    },
    // 页码改变
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pageData.page = val
      this.get_articleLists()
    }
  }
}
</script>

<style scoped>
.app-container{
  padding: 10px;
}
.demo-form-inline{
  display: flex;
  height: 50.4px;
}
.left{
  display: flex;
  flex: 1;
}
.zt{
  margin-left: 40px;
}
.gjz{
  margin-left: 25px;
}
.datanumber{
  margin-bottom: 20px;
}
/* 分页 */
.page{
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.xBox{
    position: fixed;
    top: 0;
    left: 0;
    /* transform:translateX(-50%) ; */
    z-index: 9999;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,.5);
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    }
.xBox i{
  color: #fff;
  position: absolute;
  top: 9%;
  left: 50%;
  width: 50px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  background-color: rgba(0,0,0,.5);
  border-radius: 50%;
  transform:translateX(-50%) ;
}

.videoBox{
  width: 800px;
  height: 600px;
  position: fixed;
  top:20%;
  left: 50%;
  transform:translateX(-50%) ;
}
.videoBox video{
  width: 100%;
}

.body {
  background-color: #f5f5f5;
  border-top: 1px dashed #cccccc;
  padding: 14px;
  margin-top: 10px
}
/* .el-form-item__label {
  height: 32px;
  line-height: 32px;
  padding: 0 12px 0 0;
}
.el-button {
  line-height: 1;
} */
</style>

<style>
.ql-editor{
min-height: 160px;
}
</style>
